package cn.fengshenghospital.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/file")
public class FileController {

    private static final Logger logger = LoggerFactory.getLogger(FileController.class);

    //图片上传相关代码
    @RequestMapping(value = "/imgUpLoad")
    @ResponseBody
    public String imgUpLoad(@RequestParam("img")MultipartFile file, HttpServletRequest request) {
        if (file.isEmpty()) {
            return new String("文件为空");
        }
// 获取文件名
        String fileName = file.getOriginalFilename();
        logger.info("上传的文件名为：" + fileName);
// 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        logger.info("上传的后缀名为：" + suffixName);
        if(".jpg".equals(suffixName.trim())||".png".equals(suffixName.trim())){

            // 文件上传后的路径
            String filePath = "F://IDEA//course01//src//main//resources//static//download//img//";//服务器路径
// 解决中文问题，liunx下中文路径，图片显示问题
// fileName = UUID.randomUUID() + suffixName;
            fileName=  UUID.randomUUID().toString().replace("-", "")+".png";
            File dest = new File(filePath +fileName);
// 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();

            }
            try {
                file.transferTo(dest);

            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return new String("上传的不是图片！");
    }

}
